import { Request, Response, NextFunction } from 'express';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import ApiResponse from '@/utils/api/api-response.util';
import { getLogger } from '@/utils/logger';

const consoleLogger = getLogger('common-controller',);

// 上传目录
const UPLOAD_DIR = process.env.UPLOAD_DIR || 'uploads';

// 创建上传文件存储配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 按日期分目录
    const dateDir = new Date().toISOString().slice(0, 10).replace(/-/g, '');
    const uploadDir = path.join(UPLOAD_DIR, dateDir);
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

// 文件大小限制（10MB）
const fileSize = 10 * 1024 * 1024;

// 文件过滤器
const fileFilter = (req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
  cb(null, true);
};

// 配置 multer
export const upload = multer({ 
  storage,
  limits: {
    fileSize: fileSize
  },
  fileFilter: fileFilter
});

// 错误处理中间件
export const handleMulterError = (err: any, req: Request, res: Response, next: NextFunction) => {
  if (err instanceof multer.MulterError) {
    if (err.code === 'LIMIT_FILE_SIZE') {
      return ApiResponse.error(res, '文件大小不能超过10MB', 413);
    }
    return ApiResponse.error(res, `文件上传错误: ${err.message}`, 400);
  } else if (err) {
    return ApiResponse.error(res, `文件上传失败: ${err.message}`, 500);
  }
  next();
  return;
};

class CommonController {
  /**
   * 通用上传接口
   * @param req
   * @param res
   * @param next
   */
  async uploadFile(req: Request, res: Response, next: NextFunction) {
    try {
      if (!req.file) {
        return ApiResponse.error(res, '上传文件不能为空', 400);
      }
      // 文件访问路径
      const filePath = req.file.path.replace(/\\/g, '/');
      const fileName = req.file.filename;
      const urlPrefix = process.env.BASE_URL || '';
      const url = `${urlPrefix}/uploads/${filePath.split('uploads/')[1]}`;
      // 返回结构与Java版一致
      return res.json({
        code: 200,
        msg: '操作成功',
        fileName: fileName,
        url: url
      });
    } catch (error) {
      consoleLogger.error('文件上传失败', error);
      return ApiResponse.error(res, '文件上传失败', 500);
    }
  }
}

export default new CommonController(); 